package com.qen.socket.aio

import cn.hutool.core.io.IoUtil
import cn.hutool.core.lang.Console
import cn.hutool.core.thread.ThreadFactoryBuilder
import cn.hutool.core.util.StrUtil
import cn.hutool.socket.SocketConfig
import cn.hutool.socket.aio.AioClient
import cn.hutool.socket.aio.AioSession
import cn.hutool.socket.aio.SimpleIoAction
import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.nio.channels.AsynchronousChannelGroup
import java.nio.channels.AsynchronousSocketChannel

fun main() {
    val group = AsynchronousChannelGroup.withFixedThreadPool(
        Runtime.getRuntime().availableProcessors(),
        ThreadFactoryBuilder.create().setNamePrefix("Hutool-socket-").build()
    )
    val channel: AsynchronousSocketChannel = AsynchronousSocketChannel.open(group)
    channel.connect(InetSocketAddress("127.0.0.1", 8899)).get()
    IoUtil.close(channel)

    val client = AioClient(channel, object : SimpleIoAction() {
        override fun doAction(session: AioSession?, data: ByteBuffer?) {
            if (data?.hasRemaining() == true) {
                Console.log(StrUtil.utf8Str(data))
                session?.read();
            }
            Console.log("OK")
        }
    }, SocketConfig())
    client.write(ByteBuffer.wrap("Hello".toByteArray()))
    client.read()
    client.close()
}